<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use think\Db;
use app\common\builder\ZBuilder;
/**
 * 数据统计
 * @package app\cms\admin
 */
class Statistics extends Admin
{
    /**
     * 营业额统计
     * @author shiqiang
     * @return mixed
     */
    public function store(){	
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		
		// 获取筛选
        $map = $this->getMap();
		//数据获取
        $data = input();
		
		// 数据列表
		$map[] = ['pay_status', 'in', [1,2,5]];
		
        $data_list = model('ErpGoodsOrder', 'model') -> field('store_id,sum(pay_price) as price, count(id) as order_num') -> group('store_id') -> where($map) -> paginate();
		
		$all_price = 0;
		foreach($data_list as $key => $value){
			$store = model('ErpStore') -> find($value['store_id']) -> title;
			
			$wx_price  = 0; //微信
			$zhb_price = 0; //支付宝
			$xj_price  = 0; //现金
            $ye_price  = 0; //余额

			$map = [];
			$map[] = ['store_id', '=', $value['store_id']];
			$map[] = ['pay_status', 'in', [1,2,5]];
			$order_type = model('ErpGoodsOrder', 'model') -> field('pay_type,sum(pay_price) as price') -> group('pay_type') -> where($map) -> select();
			foreach($order_type as $v){
				switch($v['pay_type']){
					case 1;
						$wx_price = $v['price'];
					break;
					case 2;
						$zhb_price = $v['price'];
					break;
					case 3;
						$xj_price = $v['price'];
					break;
					case 4;
                        $ye_price = $v['price'];
					break;
				}
			}
			
			$data_list[$key]['wx_price']  = sprintf("%01.2f", $wx_price);
			$data_list[$key]['zhb_price'] = sprintf("%01.2f", $zhb_price);
			$data_list[$key]['xj_price']  = sprintf("%01.2f", $xj_price);
			$data_list[$key]['ye_price']  = sprintf("%01.2f", $ye_price);
			$data_list[$key]['store'] 	  = $store;
			
			$all_price += $value['price'];
		}
		
		$store_day = [
			'title' => '单日营业额列表',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('store_day', ['store_id' => '__store_id__']),
		];
		
		$store_map = [];
		$store_list = model('ErpStore') -> where($store_map) -> column('id,title');
		// 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('营业额统计') // 设置页面标题
			->setPrimaryKey('store_id') // 设置主键名为username
            ->setTableName('erp_goods_order') // 设置数据表名
			->addColumns([ // 批量添加列
                ['store', '门店'],
                ['wx_price', '微信收入'],
                ['xj_price', '现金收入'],
                ['ye_price', '储值卡收入'],
				['price', '总收入'],
				['order_num', '订单总数'],
                // ['create_time', '日期'],
				['right_button', '操作', 'btn'],
            ])
			->setPageTips('当前总营业额：<span style="color:red">' . sprintf("%01.2f", $all_price) . '</span>', 'success')
			->setSearchArea([
				['select', 'store_id', '选择门店', '', '',  $store_list],
				['daterange', 'create_time', '创建时间', '', '', ['format' => 'YYYY-MM']],
            ])
			->addRightButton('custom', $store_day, true) // 批量添加右侧按钮
			->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }
	
	/**
     * 门店单日统计
     * @author shiqiang
     * @return mixed
     */
	
	public function store_day($store_id = ''){
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		// 获取筛选
        $map = $this->getMap();
		//数据获取
        $data = input();
		$url = '';
		if($store_id != ''){
			$url = 'store_day/_pop/1.html';
		}
		
		$uid = UID;//后台管理员ID
		$sotre_user = model('app\user\model\User') -> find($uid);//获取列表
		if($sotre_user['store_uid'] > 0){
			$store_id = $sotre_user['store_id'];
		}
		
		$map[] = ['pay_status', 'in', [1,2,5]];
		if($store_id > 0) $map[] = ['store_id', '=', $store_id];
		$data_list = model('ErpGoodsOrder') -> withTrashed() -> field('store_id,sum(pay_price) as price,FROM_UNIXTIME(create_time,"%Y-%m-%d") as create_time, count(id) as order_num') -> group('FROM_UNIXTIME(create_time,"%Y-%m-%d"),store_id') -> order('create_time desc') -> where($map) -> paginate();
		foreach($data_list as $key => $value){
			$store = model('ErpStore') -> find($value['store_id']) -> title;
			
			$wx_price  = 0; //微信
			$zhb_price = 0; //支付宝
			$xj_price  = 0; //现金
			$ye_price  = 0; //余额

			$start_time = strtotime($value['create_time'] . ' 00:00:00');
			$end_time   = strtotime($value['create_time'] . ' 23:59:59');
			
			$map = [];
			$map[] = ['store_id', '=', $value['store_id']];
			$map[] = ['create_time', 'between', [$start_time, $end_time]];
			$map[] = ['pay_status', 'in', [1,2,5]];
			$order_type = model('ErpGoodsOrder') -> withTrashed() -> field('pay_type,sum(pay_price) as price') -> group('pay_type') -> where($map) -> select();
			foreach($order_type as $v){
				switch($v['pay_type']){
					case 1;
						$wx_price = $v['price'];
					break;
					case 2;
						$zhb_price = $v['price'];
					break;
					case 3;
						$xj_price = $v['price'];
					break;
					case 4;
                        $ye_price = $v['price'];
					break;
				}
			}
			// $aa = model('ErpGoodsOrder') -> getLastSql();
			$data_list[$key]['wx_price']  = sprintf("%01.2f", $wx_price);
			$data_list[$key]['zhb_price'] = sprintf("%01.2f", $zhb_price);
			$data_list[$key]['xj_price']  = sprintf("%01.2f", $xj_price);
			$data_list[$key]['ye_price']  = sprintf("%01.2f", $ye_price);
			$data_list[$key]['store'] 	  = $store;
		}
		$map = [];
		if($store_id > 0) $map[] = ['id', '=', $store_id];
		$store_list = model('ErpStore') -> where($map) -> column('id,title');
		// 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('门店单日营业额统计') // 设置页面标题
			->addColumns([ // 批量添加列
                ['store', '门店'],
                ['wx_price', '当日微信收入'],
                //['zhb_price', '当日支付宝收入'],
                ['ye_price', '当日储值卡收入'],
                ['xj_price', '当日现金收入'],
				['price', '当日总收入'],
				['order_num', '当日订单总数'],
                ['create_time', '日期'],
            ])
			->setSearchArea([
				['select', 'store_id', '选择门店', '', $store_id,  $store_list],
				['daterange', 'create_time', '创建时间'],
            ], $url)
			->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
	}



    /**
     * 采购单-供货商付款统计
     * @author dou
     * @return mixed
     */

    public function supplier_money_back()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取筛选
        $map = $this->getMap();
        //数据获取
        $data = input();

        //tab
        $list_tab = [
            //'tab1' => ['title' => '全部付款单', 'url' => url('supplier_money_back', ['group' => 'tab1'])],
            'tab2' => ['title' => '未付款单', 'url' => url('supplier_money_back', ['group' => 'tab2'])],
            'tab3' => ['title' => '已付款单', 'url' => url('supplier_money_back', ['group' => 'tab3'])],
        ];

        // 数据列表
        $group = isset($data['group']) ? $data['group'] : 'tab2';
        switch ($group) {
            case 'tab1':
                $map[] = ['pay_status', 'in', [0,1]];
                break;
            case 'tab2':
                $map[] = ['pay_status', '=', 0];
                break;
            case 'tab3':
                $map[] = ['pay_status', '=', 1];
                break;
        }

        // 数据列表
        $data_list = model('ErpGoodsPurchaseOrder', 'model')
            -> alias('p')
            -> leftJoin('erp_supplier s','p.supplier_id = s.id')
            -> leftJoin('erp_goods_purchase_order_back b','b.supplier_id = s.id and b.purchase_id = p.id')
            -> where($map)
            -> field('p.*,s.title as stitle,b.id as bid,b.supplier_rebate,b.purchase_sum_cg,b.purchase_sum_rk,b.pay_sum,b.supplier_bank_account,b.pay_status,b.pay_time,b.back_remark')
            -> order('p.purchase_status desc,p.create_time desc')
            -> paginate();

        $btn_details_purchase = [
            'title' => '采购单详情',
            'icon'  => 'fa fa-fw fa-key',
            'class' => 'btn btn-xs btn-default',
            'href'  => url('erp/purchase_warehousing/details', ['id' => '__id__']),
        ];
        $btn_details_supplier = [
            'title' => '供货商详情',
            'icon'  => 'fa fa-fw fa-key',
            'class' => 'btn btn-xs btn-default',
            'href'  => url('erp/supplier/details', ['id' => '__supplier_id__']),
        ];
        $btn_supplier_money_back_edit = [
            'title' => '付款',
            'icon'  => 'fa fa-fw fa-key',
            'class' => 'btn btn-xs btn-default',
            'href'  => url('supplier_money_back_edit', ['id' => '__bid__']),
        ];
        foreach ($data_list as $key => $value){
            if(!empty($value['purchase_sum_rk']) || !empty($value['supplier_rebate'])){
                $purchase_sum_rk = $value['purchase_sum_rk']?:0;
                $supplier_rebate = $value['supplier_rebate']?:0;
                $data_list[$key]['pay_sum_yj'] = $purchase_sum_rk*(1-$supplier_rebate/100);
            }else{
                $data_list[$key]['pay_sum_yj'] = '';
            }
        }

        if($group == 'tab2'){
            // 使用ZBuilder快速创建数据表格---未付款
            return ZBuilder::make('table') // 设置页面标题
            ->setPageTitle('供货商付款单列表')
                ->setPrimaryKey('id') // 设置主键名为id
                ->setTableName('erp_goods_purchase_order_back') // 设置数据表名
                ->addColumns([ // 批量添加列
                    ['pay_status', '付款状态', 'status', '', [0 => '未付款:warning', 1 => '已汇款:success']],
                    ['title', '采购单'],
                    ['stitle', '供货商名称'],
                    ['supplier_rebate', '供货商返利(%)'],
                    ['purchase_sum_cg', '预采购总价'],
                    ['purchase_sum_rk', '实际入库总价'],
                    ['pay_sum_yj', '应付金额'],
                    /*['supplier_bank_account', '应付银行账号'],*/
                    ['back_date', '预付款日', 'date'],
                    ['right_button', '操作', 'btn']
                ])
                ->setSearchArea([
                    ['text', 'p.title', '采购单名称', 'like'],
                    ['text', 's.title', '供货商名称', 'like'],
                ])
                ->setTabNav($list_tab,  $group)
                ->addRightButton('custom', $btn_details_purchase, ['area' => ['50%', '80%']]) // 批量添加右侧按钮
                ->addRightButton('custom', $btn_details_supplier, ['area' => ['50%', '80%']]) // 批量添加右侧按钮
                ->addRightButton('custom', $btn_supplier_money_back_edit, ['area' => ['50%', '80%']]) // 批量添加右侧按钮
                ->setRowList($data_list) // 设置表格数据
                ->fetch(); // 渲染页面
        }else{
            // 使用ZBuilder快速创建数据表格----已付款
            return ZBuilder::make('table') // 设置页面标题
            ->setPageTitle('供货商付款单列表')
                ->setPrimaryKey('id') // 设置主键名为id
                ->setTableName('erp_goods_purchase_order_back') // 设置数据表名
                ->addColumns([ // 批量添加列
                    ['pay_status', '付款状态', 'status', '', [0 => '未付款:warning', 1 => '已付款:success']],
                    ['title', '采购单'],
                    ['stitle', '供货商名称'],
                    ['supplier_rebate', '供货商返利(%)'],
                    ['purchase_sum_cg', '预采购总价'],
                    ['purchase_sum_rk', '实际入库总价'],
                    ['pay_sum', '已付金额'],
                    ['supplier_bank_account', '银行账号'],
                    ['pay_time', '付款时间','datetime'],
                    ['back_remark', '备注'],
                    ['right_button', '操作', 'btn']
                ])
                ->setSearchArea([
                    ['text', 'p.title', '采购单名称', 'like'],
                    ['text', 's.title', '供货商名称', 'like'],
                ])
                ->setTabNav($list_tab,  $group)
                ->addRightButton('custom', $btn_details_purchase, ['area' => ['50%', '80%']]) // 批量添加右侧按钮
                ->addRightButton('custom', $btn_details_supplier, ['area' => ['50%', '80%']]) // 批量添加右侧按钮
                ->setRowList($data_list) // 设置表格数据
                ->fetch(); // 渲染页面
        }

    }


    public function supplier_money_back_edit($id = null)
    {
        if ($id === null) $this->error('缺少参数');
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $map['id'] = $id;
            //$data['supplier_rebate']            = isset($data['supplier_rebate']) ? $data['supplier_rebate'] :0;
            $data['pay_sum']  	                = isset($data['pay_sum_yj']) ? $data['pay_sum_yj'] : 0;
            $data['supplier_bank_account']  	= isset($data['supplier_bank_account']) ? $data['supplier_bank_account'] : '';
            $data['back_remark']                = isset($data['back_remark']) ? $data['back_remark'] : '';
            $data['pay_status']                 = 1;
            $data['pay_time']                   = time();
            unset($data['pay_sum_yj']);
            //数据验证
            if( $data['pay_sum'] == 0 || empty($data['supplier_bank_account'])){;
                $this->error('请重新检查[实际付款金额]、[付款银行账号]是否填写');
            }

            $rel = model('ErpGoodsPurchaseOrderBack','model') -> update($data, $map);

            if($rel){
                $this->success('付款成功', '', '_parent_reload');
            }else{
                $this->error($rel['message']);
            }

        }

        $info = model('ErpGoodsPurchaseOrderBack', 'model') -> find($id);
        $info['pay_sum_yj'] =$info['purchase_sum_rk']*(1-$info['supplier_rebate']/100);

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑供应商')
            ->addFormItems([
               /* ['text', 'supplier_rebate', '供货商返利(%)','如需修改请手动输入返利比例'],*/
                ['number', 'pay_sum_yj', '实际付款金额', '如需修改请手动输入金额'],
                ['text', 'supplier_bank_account', '付款银行账号','如需修改请手动输入账号信息'],
            ])
            ->addTextarea('back_remark', '备注[:如有需要请输入备注信息]')
            ->setFormData($info)
            ->fetch();
    }
}

